package one.stand.controller.home;

import com.jmp.api.dto.VersionResponse;
import io.swagger.annotations.Api;
import one.stand.model.ResultModel;
import one.stand.model.SysDictValue;
import one.stand.service.sys.SysDictValueService;
import one.stand.util.RequestContext;
import one.stand.util.RequestContextHolder;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

@Api(description = "版本更新接口")
@RestController
@RequestMapping("version")
public class VersionController {

    @Autowired
    private SysDictValueService sysDictValueService;

    @PostMapping("")
    public ResultModel<VersionResponse> version() {
        final RequestContext requestContext = RequestContextHolder.getRequestContext();
        SysDictValue sysDictValue = null;
        if (requestContext.isIos()) {
            sysDictValue = sysDictValueService.get(SysDictValueService.Type.VERSION_CRM, "APP_IOS");
        }

        boolean isUpdate = false;
        String memo = StringUtils.EMPTY;
        String apkUrl = StringUtils.EMPTY;
        if (Objects.nonNull(sysDictValue)) {
            isUpdate = requestContext.getRequest().getVersion().compareTo(sysDictValue.getValue()) < 0;
            if (StringUtils.isNoneBlank(sysDictValue.getMemo())) {
                String[] arr = sysDictValue.getMemo().split("@@");
                memo = arr[0];
                if (arr.length > 1) {
                    apkUrl = arr[1];
                }
            }
        }

        VersionResponse response = new VersionResponse();
        response.setUpdate(BooleanUtils.toInteger(isUpdate));
        response.setMemo(memo);
        response.setAppUrl(apkUrl);
        return ResultModel.success(response);
    }
}
